package com.yml.mall.user;

import com.yml.mall.currentexception.MyException;
import com.yml.mall.enums.ResponseEnum;
import com.yml.mall.user.dao.UserMapper;
import com.yml.mall.user.pojo.LoginDTO;
import com.yml.mall.user.pojo.RegisterDTO;
import com.yml.mall.user.pojo.UpdateDTO;
import com.yml.mall.user.pojo.UserDO;
import com.yml.mall.vo.ResponseVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;

@Service
public class UserServiceImpl implements UserService {
//不提倡用@AutoWired
    private final UserMapper userMapper;
    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public ResponseVO<UserDO> register(RegisterDTO registerDTO) {
        if (userMapper.countByUsername(registerDTO.getUsername()) > 0)
            throw new MyException(ResponseEnum.USERNAME_EXIST);
        if (userMapper.countByEmail(registerDTO.getEmail()) > 0)
            throw new MyException(ResponseEnum.EMAIL_EXIST);
        registerDTO.setPassword(DigestUtils.md5DigestAsHex(registerDTO.getPassword().getBytes(StandardCharsets.UTF_8)));
        UserDO userDO = new UserDO();
        BeanUtils.copyProperties(registerDTO, userDO);
        int re = userMapper.insertSelective(userDO);
        if (re == 0)
            return ResponseVO.error(ResponseEnum.ERROR);
        return ResponseVO.success();
    }

    @Override
    public ResponseVO<UserDO> login(LoginDTO loginDTO) {
        UserDO userDO = userMapper.selectByUsername(loginDTO.getUsername());
        if (userDO == null) {
            throw new MyException(ResponseEnum.UserName_Or_PASSWORD_ERROR);
        }
        if (!userDO.getPassword().equalsIgnoreCase(DigestUtils.md5DigestAsHex(loginDTO.getPassword().getBytes(StandardCharsets.UTF_8)))) {
            return ResponseVO.error(ResponseEnum.UserName_Or_PASSWORD_ERROR);
        }
        //把密码置为空
        loginDTO.setPassword("");
        userDO.setPassword("");

        return ResponseVO.success(userDO);
    }

    @Override
    public ResponseVO<UserDO> update(UpdateDTO updateDTO) {
        UserDO userDO = new UserDO();
        BeanUtils.copyProperties(updateDTO, userDO);

        int re = userMapper.insertSelective(userDO);
        if(re!=1) return ResponseVO.error(ResponseEnum.INSERT_ERROR);
        return ResponseVO.success();
    }

}
